import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/pay/subscribe_entity.dart';
import 'package:ball_lion/server/api/other_api.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/base/wqs_button.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';

class SubscribleCardSheet extends StatefulWidget {
  const SubscribleCardSheet({super.key, required this.cards, this.cardSelect});

  final List<SubscribleCardEntity> cards;
  final SubscribleCardEntity? cardSelect;

  @override
  State<SubscribleCardSheet> createState() => _SubscribleCardSheetState();
}

class _SubscribleCardSheetState extends State<SubscribleCardSheet> {
  List<SubscribleCardEntity> get cards => widget.cards;
  SubscribleCardEntity? get cardSelect => widget.cardSelect;
  String tip = "";

  @override
  void initState() {
    getTip();
    super.initState();
  }

  Future getTip() async {
    var tips = await OtherApi.getAppList("app_res_tips");
    tip = tips
            ?.firstWhere((element) => element.button == "use_subs_tip")
            .content ??
        "";
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 461,
      clipBehavior: Clip.hardEdge,
      decoration: const BoxDecoration(
          color: Colours.greyF7,
          borderRadius: BorderRadius.vertical(top: Radius.circular(10))),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            height: 63.5,
            color: Colors.white,
            padding: const EdgeInsets.symmetric(horizontal: 12),
            child: Row(
              children: [
                Expanded(
                    child: Row(
                  children: [
                    Image.asset(
                      width: 24,
                      Utils.getImgPath("arrow_back.png"),
                    ).tap(() {
                      Get.back();
                    })
                  ],
                )),
                const QsText("选择订阅卡"),
                Expanded(
                    child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    QsButton(
                      onPressed: () {
                        if (tip.hasValue) {
                          Get.dialog(QsDialog.single("订阅卡使用说明",
                              content: tip, confirmText: "我知道了"));
                        }
                      },
                      text: "使用说明",
                      foregroundColor: Colours.grey666666,
                      textStyle: const TextStyle(
                          fontSize: 14, fontWeight: FontWeight.w400),
                    )
                  ],
                ))
              ],
            ),
          ),
          cards.isEmpty
              ? const Expanded(
                  child: Center(
                  child: NoDataWidget(tip: "无可用订阅卡"),
                ))
              : Expanded(
                  child: ListView.builder(
                  padding: const EdgeInsets.fromLTRB(16, 20, 16, 12),
                  itemCount: cards.length,
                  itemBuilder: (context, index) {
                    final entity = cards[index];
                    bool isEnd = index == cards.length - 1;
                    bool selectable =
                        (entity.enable == true && entity.invalid == true);
                    return SubscribleItemWidget(
                            selectable: selectable,
                            selected: entity.id == cardSelect?.id,
                            cardItem: entity)
                        .marginOnly(bottom: isEnd ? 0 : 10)
                        .tap(() {
                      if (selectable) {
                        Get.back(result: entity);
                      }
                    });
                  },
                )),
          const SizedBox(height: 10),
          Container(
            alignment: Alignment.center,
            margin: const EdgeInsets.symmetric(horizontal: 16),
            height: 44,
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(4)),
            child: const QsText("不使订阅卡"),
          ).tap(() {
            Get.back(result: false);
          }),
          const SizedBox(height: 20)
        ],
      ),
    );
  }
}

class DashSeparator extends StatelessWidget {
  const DashSeparator({super.key, this.height = 1, this.color = Colors.black});
  final double height;
  final Color color;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final boxWidth = constraints.constrainWidth();
        const dashWidth = 8.0;
        final dashHeight = height;
        final dashCount = (boxWidth / (2 * dashWidth)).floor();
        return Flex(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          direction: Axis.horizontal,
          children: List.generate(dashCount, (_) {
            return SizedBox(
              width: dashWidth,
              height: dashHeight,
              child: DecoratedBox(
                decoration: BoxDecoration(color: color),
              ),
            );
          }),
        );
      },
    );
  }
}

class SubscribleItemWidget extends StatefulWidget {
  const SubscribleItemWidget(
      {super.key,
      this.selectable = false,
      this.selected = false,
      this.cardItem});

  final bool selectable;
  final bool selected;
  final SubscribleCardEntity? cardItem;

  @override
  State<SubscribleItemWidget> createState() => _SubscribleItemWidgetState();
}

class _SubscribleItemWidgetState extends State<SubscribleItemWidget> {
  SubscribleCardEntity? get cardItem => widget.cardItem;
  bool get selectable => widget.selectable;
  bool get selected => widget.selected;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final disableColor = (selectable ? null : Colours.grey99);
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          image: DecorationImage(
              image: AssetImage(Utils.getImgPath(selectable
                  ? "subcard_bg_enable.png"
                  : "subcard_bg_disable.png")),
              isAntiAlias: true,
              fit: BoxFit.cover)),
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: Column(
        children: [
          SizedBox(
            height: 82.5,
            child: Column(
              children: [
                Expanded(
                  flex: 7,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      QsText(
                        '专家订阅卡 ${cardItem?.usedDesc ?? ""}',
                        fontSize: 12,
                        color: selectable ? Colours.goldFFEEC8 : Colours.white,
                        fontWeight: FontWeight.w600,
                      ).marginOnly(bottom: 10),
                      const Spacer(),
                      _buildCheckImageOrInvalidText(
                          selectable, selected, cardItem?.invalid ?? false)
                    ],
                  ),
                ),
                Expanded(
                  flex: 7,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      QsText(
                        cardItem?.name ?? "",
                        fontSize: 16,
                        color: disableColor ?? Colours.grey66,
                        fontWeight: FontWeight.w600,
                      ).marginOnly(bottom: 5),
                    ],
                  ),
                ),
                if (cardItem?.expire != null) const Spacer(),
                Expanded(
                  flex: 5,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      QsText(
                        "有效期至${DateTimeUtils.formatTimeStamp(cardItem!.expire!, 'yyyy-MM-dd')}",
                        color: disableColor ?? Colours.main,
                        fontSize: 12,
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
          const DashSeparator(color: Colours.greyEE),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Container(
                  padding: const EdgeInsets.symmetric(vertical: 8),
                  alignment: Alignment.centerLeft,
                  constraints: const BoxConstraints(minHeight: 40),
                  child: QsText(
                    cardItem?.desc ?? "",
                    fontSize: 12,
                    color: disableColor ?? Colours.grey66,
                  ),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

Widget _buildCheckImageOrInvalidText(
    bool selectable, bool selected, bool invalid) {
  if (selectable) {
    final imagePath = Utils.getImgPath(selected ? 'check.png' : 'uncheck.png');
    return Image.asset(
      imagePath,
      width: 14,
      height: 14,
    );
  } else if (invalid == false) {
    return const QsText(
      "已过期",
      color: Colours.grey66,
      fontSize: 12,
    );
  } else {
    return const SizedBox.shrink(); // or any other widget if needed
  }
}
